#include "include/widgets/stock_info_widget.hpp"
#include <QDebug>
#include <QHeaderView>
#include <QtCharts/QDateTimeAxis>
#include <QtCharts/QValueAxis>

StockInfoWidget::StockInfoWidget(MarketDataManager *marketManager,
                                 QWidget *parent)
    : QWidget(parent), m_marketManager(marketManager), m_currentStockCode("") {
  setupUI();
  setupConnections();
  refreshStockTable();
}

void StockInfoWidget::setupUI() {
  // 创建主布局
  auto *mainLayout = new QVBoxLayout(this);

  // 创建股票表格
  m_stockTableView = new QTableView(this);
  m_stockModel = new QStandardItemModel(this);
  m_stockModel->setColumnCount(4);
  m_stockModel->setHorizontalHeaderLabels(
      {"代码", "名称", "价格", "涨跌幅(%)"});

  m_stockTableView->setModel(m_stockModel);
  m_stockTableView->horizontalHeader()->setSectionResizeMode(
      QHeaderView::Stretch);
  m_stockTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
  m_stockTableView->setSelectionMode(QAbstractItemView::SingleSelection);
  m_stockTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
  m_stockTableView->setSortingEnabled(true);

  // 设置委托来格式化显示
  m_stockDelegate = new StockTableDelegate(this);
  m_stockTableView->setItemDelegate(m_stockDelegate);

  // 刷新按钮
  auto *buttonLayout = new QHBoxLayout();
  m_refreshButton = new QPushButton("刷新", this);
  buttonLayout->addStretch();
  buttonLayout->addWidget(m_refreshButton);

  // 创建图表视图
  m_chart = new QChart();
  m_chart->legend()->hide();
  m_chart->setTitle("股票价格走势");

  m_chartView = new QChartView(m_chart, this);
  m_chartView->setRenderHint(QPainter::Antialiasing);
  m_chartView->setMinimumHeight(200);

  // 将控件添加到布局
  mainLayout->addWidget(m_stockTableView);
  mainLayout->addLayout(buttonLayout);
  mainLayout->addWidget(m_chartView);
}

void StockInfoWidget::setupConnections() {
  connect(m_marketManager, &MarketDataManager::marketUpdated, this,
          &StockInfoWidget::onMarketUpdated);
  connect(m_refreshButton, &QPushButton::clicked, this,
          &StockInfoWidget::refreshStockTable);

  connect(m_stockTableView, &QTableView::clicked, this,
          [this](const QModelIndex &index) {
            int row = index.row();
            QString stockCode = m_stockModel->item(row, 0)->text();
            QString stockName = m_stockModel->item(row, 1)->text();
            double price =
                m_stockModel->item(row, 2)->data(Qt::DisplayRole).toDouble();

            emit stockSelected(stockCode, stockName, price);
            showStockChart(stockCode);
          });
}

void StockInfoWidget::refreshStockTable() {
  // 清空表格
  try {
    m_stockModel->removeRows(0, m_stockModel->rowCount());
  } catch (const std::exception &e) {
    qDebug() << "清空股票表格失败:" << e.what();
    return;
  }
  // 添加股票数据
  const QVector<Stock> &stocks = m_marketManager->getStocks();
  for (const auto &stock : stocks) {
    QList<QStandardItem *> row;
    row.append(new QStandardItem(stock.code));
    row.append(new QStandardItem(stock.name));

    auto *priceItem = new QStandardItem();
    priceItem->setData(stock.price, Qt::DisplayRole);
    row.append(priceItem);

    auto *changeItem = new QStandardItem();
    changeItem->setData(stock.change, Qt::DisplayRole);
    row.append(changeItem);

    m_stockModel->appendRow(row);
  }

  // 如果有选中的股票，更新图表
  if (!m_currentStockCode.isEmpty()) {
    showStockChart(m_currentStockCode);
  }
}

void StockInfoWidget::onMarketUpdated() { refreshStockTable(); }

void StockInfoWidget::showStockChart(const QString &stockCode) {
  m_currentStockCode = stockCode;

  // 获取股票数据
  Stock *stock = m_marketManager->findStock(stockCode);
  if (!stock) {
    return;
  }

  try {
    // 清空旧图表
    m_chart->removeAllSeries();
    // 移除所有横轴
    const auto xAxes = m_chart->axes(Qt::Horizontal);
    for (QAbstractAxis *axis : xAxes) {
      m_chart->removeAxis(axis);
    }
    // 移除所有纵轴
    const auto yAxes = m_chart->axes(Qt::Vertical);
    for (QAbstractAxis *axis : yAxes) {
      m_chart->removeAxis(axis);
    }
  } catch (const std::exception &e) {
    qDebug() << "清空图表失败:" << e.what();
    return;
  }
  // 创建线系列
  QLineSeries *series = new QLineSeries();
  series->setName(stock->name);

  // 添加历史价格点
  const QVector<double> &prices = stock->getPriceHistory();
  const QVector<QDateTime> &times = stock->getTimeHistory();

  if (prices.isEmpty() || times.isEmpty() || prices.size() != times.size()) {
    return;
  }

  double minPrice = std::numeric_limits<double>::max();
  double maxPrice = std::numeric_limits<double>::min();

  for (int i = 0; i < prices.size(); ++i) {
    series->append(times[i].toMSecsSinceEpoch(), prices[i]);
    minPrice = std::min(minPrice, prices[i]);
    maxPrice = std::max(maxPrice, prices[i]);
  }

  // 添加系列到图表
  m_chart->addSeries(series);

  // 创建坐标轴
  QDateTimeAxis *axisX = new QDateTimeAxis;
  axisX->setTickCount(5);
  axisX->setFormat("HH:mm:ss");
  axisX->setTitleText("时间");

  QValueAxis *axisY = new QValueAxis;
  axisY->setLabelFormat("%.2f");
  axisY->setTitleText("价格");

  // 设置价格范围，稍微增加边距
  double margin = (maxPrice - minPrice) * 0.1;
  if (margin < 0.01)
    margin = 0.01;
  axisY->setRange(minPrice - margin, maxPrice + margin);

  // 添加坐标轴
  m_chart->addAxis(axisX, Qt::AlignBottom);
  m_chart->addAxis(axisY, Qt::AlignLeft);
  series->attachAxis(axisX);
  series->attachAxis(axisY);

  // 设置图表标题
  m_chart->setTitle(QString("%1 (%2) 价格走势").arg(stock->name, stock->code));
}

QTableView *StockInfoWidget::getStockTableView() const {
  return m_stockTableView;
}
